<template>
	<view class="main">
        <view class="form">
<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<up-form
            labelPosition="top"
            :model="formData"
            :rules="formRules"
            ref="formRef"
            :labelStyle="{
                fontSize: '24rpx',
                color: '#999'
            }"
		>
			<up-form-item
                label="姓名"
                labelWidth="500rpx"
                prop="receiverName"
                borderBottom
			>
				<up-input class="address-input" maxlength="20" v-model.trim="formData.receiverName" border="none" placeholder="请输入姓名" ></up-input>
			</up-form-item>
			<up-form-item
                label="手机号码"
                labelWidth="500rpx"
                prop="receiverPhone"
                borderBottom
			>
				<up-input class="address-input" maxlength="11" v-model.trim="formData.receiverPhone" type="number" border="none" placeholder="请输入手机号码"></up-input>
			</up-form-item>
			<up-form-item
                label="详细地址"
                labelWidth="500rpx"
                prop="addressDetail"
                borderBottom
			>
                <up-textarea class="address-input" maxlength="150" v-model.trim="formData.addressDetail" placeholder="XX省XX市XX区XX路XX号" ></up-textarea>
			</up-form-item>
            
			<up-form-item
                label="地址标签"
                labelWidth="500rpx"
                prop="tag"
                borderBottom
			>
				<up-input class="address-input" maxlength="5" v-model.trim="formData.tag" border="none" placeholder="例如：公司" ></up-input>
			</up-form-item>
			<up-form-item
                label=""
                labelWidth="500rpx"
                prop="isDefault"
			>
                <up-checkbox
                    :usedAlone="true"
                    label="设置为默认地址"
                    name="agree"
                    :checked="formData.isDefault === 1"
                    labelSize="24rpx"
                    size="34rpx"
                    iconSize="24rpx"
                    @change="handleIsDefault"
                >
                </up-checkbox>
			</up-form-item>
        </up-form>
        </view>
		
        <view class="page-footer" @click="handelToAdd">
            <view class="footer-content">{{formData.id ? '修改地址' : '添加地址'}}</view>
        </view>
	</view>
</template>
<script setup>
import { reactive, ref, computed } from 'vue'
import { useStore } from 'vuex'
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { addAddressApi, updateAddressApi} from '@/api/user'

const store = useStore()

// 使用 ref 创建响应式引用  
const formRef = ref(null);  
const formData = ref({
  "addressDetail": "",
  "isDefault": 0,
  "receiverName": "",
  "receiverPhone": "",
  "tag": ""
})
const addressList = computed(() => store.getters['user/addressList']);

onLoad((options) => {
    if(options.id) {
        const match = addressList.value.find(item => item.id == options.id)
        if(match) {
            formData.value = { ...match }
        }
    }
    // console.log(JSON.stringify(addressList.value))
})

const formRules = reactive({
    'receiverName': {  
      type: 'string',  
      required: true,  
      message: '请填写姓名',  
      trigger: ['blur', 'change'],  
    },
    'receiverPhone': {  
      type: 'string',  
      required: true,  
      message: '请填手机号码',  
      trigger: ['blur', 'change'],  
    },
    'addressDetail': {  
      type: 'string',  
      required: true,  
      message: '请填详细地址',  
      trigger: ['blur', 'change'],  
    },
    'tag': {  
      type: 'string',  
      required: true,  
      message: '请填地址标签',  
      trigger: ['blur', 'change'],  
    }
}) 
function handleIsDefault(e){
    formData.value.isDefault = e ? 1 : 0
}
function handelToAdd(){
    formRef.value.validate().then(valid => {  
        // debugger
        if (valid) {  
            editData()
        } else {  
            uni.$u.toast('请完善信息')
        }  
    }).catch((e) => {  
        console.error(e)
        // 处理验证错误  
        uni.$u.toast('请完善信息')
    });  
}
async function editData(){
    try {    
        uni.showLoading()
        if(!formData.value?.id) {
            await addAddressApi({...formData.value})
            uni.$u.toast('添加地址成功')
        } else {
            await updateAddressApi({...formData.value})
            uni.$u.toast('修改地址成功')
        }
        store.dispatch('user/getAddressList')
        uni.navigateBack()
    } finally {
        uni.hideLoading()
    }

}
</script>
<style lang='scss' scoped>
.main{
  min-height: 100vh;
  background: #F4F6F8;
  padding-top: 20rpx;
  padding-bottom: calc(140rpx + var(--safe-area-inset-bottom));
  .form{
    margin: 0 20rpx;
    background: #fff;
    padding: 0 32rpx;
    border-radius: 20rpx;
    .address-input{
        font-weight: 500;
        font-size: 26rpx;
        color: #666;
        height: 60rpx;
        padding: 10rpx 0;
        line-height: 40rpx;
        margin-top: 10rpx;
    }
  }
    .page-footer{
        position: fixed;
        bottom: 0;
        left: 0;
        background: #FFFFFF;
        box-sizing: content-box;
        padding-bottom: var(--safe-area-inset-bottom);
        align-items: center;
        .footer-content{
            width: 100vw;
            padding: 24rpx 0;
            background: #FF8F1F;
            height: 98rpx;
            font-weight: 400;
            font-size: 32rpx;
            color: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}
</style>